<template>
	<nav-header type="noHeader" title="我的">
		<view class="flex justify-between items-center m-6">
			<view class="flex items-center" @click="()=>{
				if (user.token) $util.myNavigateTo('/pages_mine/edit_user')
			}">
				<u-avatar shape="square" :src="$util.formatImageIdUrl(user.avatarUrl)" size="50"></u-avatar>
				<text class="text-lg font-bold pl-2_5 pr-1" v-text="user.token? (user.userName || '微信未授权'):'游客'"></text>
				<u-icon v-if="user.token" name="edit-pen" size="20" color="white" class="pt-1 pl-1"></u-icon>
				<!-- <image v-if="user.token" src="../../static/common/grand.png" class="w-4 h-4"></image> -->
			</view>
			<view class="bg-theme px-2_5 py-1 rounded-lg text-sm text-white" style="border: 2px solid white;"
				@click="userAuth" v-text="user.token? '注销':'登录'"></view>
		</view>
		<view class="bg-white grid grid-cols-3 gap-5 p-4 m-4 rounded-lg shadow-lg">
			<view v-for="(config,key) in funcObj" :key="key" v-if="config.isShow" class="text-center"
				@tap="$util.myNavigateTo(config.navUrl)">
				<i :class="config.icon" class="iconfont text-black-33 text-2xl"></i>
				<text class="block text-gray-66 text-sm pt-1" v-text="config.name"></text>
			</view>
		</view>
		<view class="mx-6">
			<view v-for="(config,key) in funcObj2" :key="key" v-if="config.isShow"
				class="flex justify-between items-center py-3" @click="()=>{
				if (config.navUrl) $util.myNavigateTo(config.navUrl)
			}">
				<view class="flex items-center">
					<i :class="config.icon" class="iconfont text-gray-66 text-xl pt-0_5"></i>
					<text class="text-gray-66 pl-2" v-text="config.name"></text>
				</view>
				<template v-if="key == 'fnc1' && config.num > 0">
					<view class="bg-theme rounded-full px-2 text-sm" v-text="config.num"></view>
				</template>
				<template v-else-if="key == 'fnc3' && config.val > -1">
					<text class="text-gray-99 text-sm" v-text="authArr[config.val]"></text>
				</template>
				<template v-else-if="key == 'fnc5'">
					<button plain open-type="contact">
						<u-icon name="arrow-right"></u-icon>
					</button>
				</template>
				<template v-else>
					<u-icon name="arrow-right"></u-icon>
				</template>
			</view>
		</view>
		<u-popup :show="wxAuthShow" :round="16" :safeAreaInsetBottom="false" @close="wxAuthShow = false"
			:closeable="true">
			<view class="py-6">
				<view class="text-lg text-center text-black-33 font-bold mb-4">微信授权</view>
				<view class="flex items-center justify-center mb-2_5">
					<image src="@/static/common/auth.png" class="mr-2" style="width: 23px;height: 23px;"></image>
					<text class="text-lg text-black-33 font-bold">小程序申请获取以下权限</text>
				</view>
				<view class="text-gray-66 text-center mb-6 text-sm">获取您的公开信息(呢称,头像,手机)</view>
				<view class="grid grid-cols-3 gap-4 mx-4">
					<u-button :plain="true" text="暂不授权" @click="wxAuthShow = false"
						:customStyle="{height: '35px'}"></u-button>
					<u-button type="primary" :hairline="true" text="授权手机号" @getphonenumber="getPhoneAuth"
						openType="getPhoneNumber" @error="$util.toast('获取手机号授权失败.')"
						:customStyle="{height: '35px',color: 'white' ,backgroundColor: '#2d58cb', border: 'none'}"></u-button>
					<u-button type="primary" :hairline="true" text="授权呢称头像" @click="getUserAuth()"
						:customStyle="{height: '35px',color: 'white' ,backgroundColor: '#2d58cb', border: 'none'}"></u-button>
				</view>
			</view>
		</u-popup>
	</nav-header>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import NavHeader from '@/components/nav_header.vue'
	import * as authUserApi from '@/interface/auth/authUserApi.js'
	import * as noticeApi from '@/interface/junchuang/notice.js'
	export default {
		components: {
			NavHeader
		},
		data() {
			const v = this
			const {
				envVersion
			} = v.$store.state.system
			let isShow = 'develop,release'.indexOf(envVersion) > -1 ? true : false
			return {
				isLogin: false,
				wxAuthShow: false,
				authArr: ['未认证', '审核中', '已认证', '审核不通过'],
				funcObj: {
					fnc1: {
						name: '我的活动',
						isShow: true,
						icon: 'icon-wodehuodong',
						navUrl: '/pages_mine/activity'
					},
					fnc2: {
						name: '',
						isShow: true,
						icon: '',
            navUrl: ''
					},
          fnc3: {
            name: '通知中心',
            isShow: true,
            icon: 'icon-pinglunxiao',
            num: 0,
            navUrl: '/pages_mine/notice'
          },
				},
				funcObj2: {

					fnc5: {
						name: '客服助手',
						isShow: true,
						icon: 'icon-kefu1',
						navUrl: ''
					},
					fnc7: {
						name: '关于我们',
						isShow: true,
						icon: 'icon-guanyuwomen-03',
						navUrl: '/pages/common/article_detail?code=about_us'
					},
				},
			}
		},
		computed: {
			...mapState({
				user: state => state.user,
				system: state => state.system
			})
		},
		onShow() {
      this.$util.openShare();
			this.checkUserAuth()
		},
		methods: {
			userAuth() {
				const v = this
				let token = uni.getStorageSync('token')
				if (token) {
					v.$util.showModal('退出登陆', '确认要退出登陆吗？', true, '确定', '取消', (res) => {
						v.funcObj2.fnc1.num = 0
						v.funcObj2.fnc3.val = -1
						v.$store.dispatch('userLogout');
					}, (res) => {
						return
					})
				} else {
					if (v.isLogin) return;
					//v.tyrzLogin()
					 v.isLogin = true;
					 v.$util.showLoading('用户登录中..')
					 let authUserRes = authUserApi.userLogin()
					 if (authUserRes) {
					 	authUserRes.then(res => {
					 		if (res.success) v.setUserAuth(res)
					 	}).finally(()=>{
					 		reset()
					 	})
					 } else {
					 	reset()
					 }
				}

				function reset() {
					v.isLogin = false
					v.$util.hideLoading()
				}
			},
			// 通过统一认证系统登录
			tyrzLogin() {
				const v = this
				v.isLogin = true
				// 跳转粤信签页面
				wx.navigateToMiniProgram({
					appId: v.$config.yxq_appId,
					path: 'pages/authenticate/index/index?from=miniProgram&responseType=code&appName=' + v.$config.app_name,
					extraData: {
						from: 'miniProgram',
						appName: v.$config.app_name,
						responseType: 'code'
					},
					complete() {
						v.isLogin = false
						v.checkUserAuth()
					}
				})
			},
			setUserAuth(res) {
				const v = this
				uni.setStorageSync('token', res.data.accessToken)
				authUserApi.getUserInfo().then(userRes => {
					if (res.success) {
						const {
							id,
							nickName,
							avatarUrl,
							status,
							authStatus,
							phone
						} = userRes.data
						uni.setStorageSync("userInfo", userRes.data);
						v.$store.commit('setStateAttr', {
							userId: id,
							phone: phone,
							userName: nickName,
							avatarUrl: avatarUrl,
							token: res.data.accessToken
						})
					}
				})
			},
			getUserAuth() {
				const v = this
				v.$util.showLoading('微信授权中..')
				wx.getUserProfile({
					desc: '用于完善用户资料',
					lang: 'zh_CN',
					success: (res) => {
						v.$util.hideLoading()
						const {nickName,avatarUrl} = res.userInfo
						v.$store.dispatch('updateUserInfo', {
							status: '1',
							type: 'user',
							userName: nickName,
							avatarUrl: avatarUrl
						})
						authUserApi.updateUserInfo({
							nickName: nickName,
							avatarUrl: avatarUrl,
							status: '1'
						})
						v.$u.toast('获取微信授权信息成功.')
					},
					fail: (res) => {
						v.$util.hideLoading()
						v.$u.toast('无法获取微信授权信息,请稍后再试.')
					}
				})
			},
			getPhoneAuth(e) {
				const v = this
				const {
					encryptedData,
					iv,
					errMsg
				} = e.detail
				if (errMsg === 'getPhoneNumber:ok') {
					authUserApi.getPhone(encryptedData, iv).then(({
						data
					}) => {
						v.$store.dispatch('updateUserInfo', {
							type: 'phone',
							phone: data.purePhoneNumber
						})
						let userInfo = uni.getStorageSync('userInfo')
						userInfo.phone = data.purePhoneNumber
						authUserApi.updateUserInfo({
							...userInfo
						})
						v.$u.toast('获取微信授权信息成功.')
					})
				}
			},
			checkUserAuth() {
				const v = this
				let token = uni.getStorageSync('token')
				if (!token) return
				noticeApi.getNoticePageList({
					pageNum: 1,
					sendType: '0',
					readStatus: '0'
				}).then(res => {
					if (res.success) v.funcObj2.fnc1.num = res.data.total
				})
				authUserApi.getUserInfo().then(res => {
					if (res.success) {
						const { avatarUrl,status,authStatus } = res.data
						v.funcObj2.fnc3.val = parseInt(authStatus)
						// 提示微信授权
						// v.wxAuthShow = status == '0' && !avatarUrl
					}
				})
			}
		}
	}
</script>

<style type="scoped">
	page{
		background-color: #f7f7f7;
	}

	/deep/ .u-avatar,/deep/ .u-avatar__image {
		border-radius: 12px !important;
	}

	button[plain], button::after {
		flex: 1 1 0%;
		display: flex !important;
		flex-direction: row-reverse;
		border: none !important;
		padding-right: 0px !important;
		margin-right: 0px !important;
	}
</style>
